package com.security.control.browser.authentication;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.security.control.core.properties.SecurityProperties;
import com.security.control.core.support.AuthenticateResponseType;
import com.security.control.core.support.SimpleResponseEntity;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author imoot@gamil.com
 * @date 2018/12/18 0018 14:45
 * ----自定义登录成功处理类
 */
@Component("myAuthenticationSuccessHandler")
public class MyAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

    private Logger log = LoggerFactory.getLogger(MyAuthenticationSuccessHandler.class);

    @Autowired
    private SecurityProperties securityProperties;

    @Autowired
    private ObjectMapper objectMapper;

    private RequestCache requestCache = new HttpSessionRequestCache();

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        log.info("登录成功");
        if (AuthenticateResponseType.JSON.equals(securityProperties.getBrowserProperties().getAuthenticateResponseType())) {
            response.setContentType("application/json;charset=UTF-8");
            String type = authentication.getClass().getSimpleName();
            //把用户权限类名封入响应类后用ObjectMapper转换为json字符串写入response
            response.getWriter().write(objectMapper.writeValueAsString(new SimpleResponseEntity(type)));
        } else {
            //如果设置了com.security.control.browser.signInSuccessUrl，那么总是跳转到设置的地址上
            //反之，则尝试跳转到登录之前访问的地址上（如果登录之前访问的地址为空，则跳转到网站根路径上）
            if(StringUtils.isNotBlank(securityProperties.getBrowserProperties().getSignInSuccessUrl())){
                requestCache.removeRequest(request,response);
                setAlwaysUseDefaultTargetUrl(true);
                setDefaultTargetUrl(securityProperties.getBrowserProperties().getSignInSuccessUrl());
            }
            super.onAuthenticationSuccess(request, response, authentication);
        }
    }
}
